<?php

namespace app\store\controller;


require 'vendor/autoload.php';

use app\store\model\Orders as OrderModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 订单管理
 * Class Order
 * @package app\store\controller
 */
class Orders extends Controller
{
    /**
     * 全部订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        return $this->getList('全部订单列表', 'all');
    }

    /**
     * 待付款订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function pay()
    {
        return $this->getList('己下单 待付款', 'pay');
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function cancelled(){
        return $this->getList('已下单后取消', 'cancelled');
    }

    /**
     * 已取消订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function inspect_list()
    {
        return $this->getList('已支付 待核销订单列表', 'inspect');
    }

    /**
     * 已核销 待确认订单列表
     * @return mixed
     */
    public function PaidCancellation(){
        return $this->getList('已支付后取消', 'PaidCancellation');
    }

    /**
     * 已完成订单列表
     * @return mixed
     */
    public function complete(){
        return $this->getList('已完成', 'complete');
    }

    /**
     * 订单列表
     * @param $title
     * @param $dataType
     * @return mixed
     * @throws \think\exception\DbException
     */
    private function getList($title, $dataType)
    {
        $model = new OrderModel;
       
        $list = $model->getList($dataType, $this->request->param());

        $arr = [];
        foreach ( $list as $data ){
            $array = $model->list($data['id']);
            $arr[] = $array;
        }
        return $this->fetch('index',  compact('dataType','title','list','arr'));
    }

    /**
     * 订单详情
     * @param $id
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function detail($id)
    {
        $model = new OrderModel;
        $detail = $model->detail($id);
        $list = [];
        $list[] = $model->list($id);
        return $this->fetch('detail',compact('detail','list'));
    }

    /**
     * 订单导出
     * @param string $dataType
     * @throws \think\exception\DbException
     */
    public function export($dataType){
        $model = new OrderModel;
        $list = $model->getList($dataType, $this->request->param());
        $arr = [];
        foreach ( $list as $data ){
            $array = $model->list($data['id']);
            $arr[] = $array;
        }
        return $this->orderList($arr);
    }

    /**
     * 订单导出
     * @param string $dataType
     * @throws \think\exception\DbException
     */
    public function orderList($list){

        //让程序一直运行
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '700M');

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('订单信息');

        $worksheet->setCellValueByColumnAndRow(1, 1, '订单信息');
        $worksheet->setCellValueByColumnAndRow(1, 2, '订单号');
        $worksheet->setCellValueByColumnAndRow(2, 2, '交易号');
        $worksheet->setCellValueByColumnAndRow(3, 2, '订单总额');
        $worksheet->setCellValueByColumnAndRow(4, 2, '支付方式');
        $worksheet->setCellValueByColumnAndRow(5, 2, '下单时间');
        $worksheet->setCellValueByColumnAndRow(6, 2, '买家');
        $worksheet->setCellValueByColumnAndRow(7, 2, '付款状态');
        $worksheet->setCellValueByColumnAndRow(8,2, '付款时间');
        $worksheet->setCellValueByColumnAndRow(9,2, '订单状态');

        $worksheet->getColumnDimension('A')->setWidth(25);
        $worksheet->getColumnDimension('B')->setWidth(25);
        $worksheet->getColumnDimension('C')->setWidth(25);
        $worksheet->getColumnDimension('D')->setWidth(25);
        $worksheet->getColumnDimension('E')->setWidth(25);
        $worksheet->getColumnDimension('F')->setWidth(25);
        $worksheet->getColumnDimension('G')->setWidth(25);
        $worksheet->getColumnDimension('H')->setWidth(25);
        $worksheet->getColumnDimension('I')->setWidth(25);
        
        //合并单元格
        $worksheet->mergeCells('A1:I1');
        $styleArray = [
            'font' => [
                'bold' => true
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        //设置单元格样式
        $worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(28);

        $worksheet->getStyle('A2:I2')->applyFromArray($styleArray)->getFont()->setSize(14);
        $len = 3;
        foreach ($list as $order) {
            $name = 0;
            foreach ($order['OrderTicket'] as $data){
                $name += (int)$data['price'] * (int)$data['num'];
            }
            $worksheet->setCellValueByColumnAndRow(1, $len, $this->filterValue($order[0]['order_no']));
            $worksheet->setCellValueByColumnAndRow(2, $len, $this->filterValue($order[0]['transaction_no']));
            $worksheet->setCellValueByColumnAndRow(3, $len, $this->filterValue($name));
            $worksheet->setCellValueByColumnAndRow(4, $len, $this->filterValue($order[0]['pay_type'] == 10 ? '支付宝支付' : '微信支付'));
            $worksheet->setCellValueByColumnAndRow(5, $len, $this->filterTime($order[0]['create_time']));
            $worksheet->setCellValueByColumnAndRow(6, $len, $this->filterValue($order[0]['nickName']));
            $worksheet->setCellValueByColumnAndRow(7, $len, $this->filterValue($order[0]['pay_status'] == 1 ? '未付款' : '已付款'));
            $worksheet->setCellValueByColumnAndRow(8,$len, $this->filterTime($order[0]['pay_time']));
            $worksheet->setCellValueByColumnAndRow(9,$len, $this->filterValue($this->status($order[0]['order_status'])));
            $len++;
        }

        $styleArrayBody = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => '666666'],
                ],
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $total_rows = $len + 2;
        //添加所有边框/居中
        $worksheet->getStyle('A1:I'.$total_rows)->applyFromArray($styleArrayBody);

        // 下载
        $filename = '订单信息.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    /**
     * 日期值过滤
     * @param $value
     * @return string
     */
    private function filterTime($value)
    {
        if (!$value) return '';
        return $this->filterValue(date('Y-m-d H:i:s', $value));
    }

    /**
     * 订单状态
     * @param $order
     * @return mixed|string
     */
    public function status($order){
        if( $order == 10 )  {
            $order = '已下单 待支付';
        }else if( $order == 11 ){
            $order = '已下单后取消';
        } else if( $order == 20 ){
            $order = '已支付 待核销';
        } else if( $order == 21 ){
            $order = '已支付后取消';
        } else if( $order == 80 ){
            $order = '已完成';
        }
        return $order;
    }

    /**
     * 用户付款后进行拆分
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function payment($id){
        $Orders = new \app\store\model\Orders();
        $list = $Orders->where('id',$id)->find();
        $list->save([
            'order_status'=>20,
            'pay_status' => 2
        ]);
        return $this->renderSuccess('操作成功');
    }

}